package ar.tuc.unsta.campus.weather.unstaWeatherUpload.model;

import java.io.File;

import org.apache.commons.vfs2.FileSystemException;

import ar.tuc.unsta.campus.weather.unstaWeatherUpload.view.util.FileWatcher;

public class FileUploaderModel {

	RunnableWatcher runnableWatcher;
	
	public void listenToFile(File file){
		runnableWatcher = new RunnableWatcher(file);
		runnableWatcher.startWatching();
	}
	
	public void stopListening(){
		if(runnableWatcher != null)
			runnableWatcher.stopWatching();
	}
	
}

class RunnableWatcher implements Runnable{
	
	private Thread thread;
	private File fileToWatch;
	private FileWatcher fileWatcher;
	
	RunnableWatcher(File file){
		fileToWatch = file;
		fileWatcher = new FileWatcher();
		System.out.println("Creating watcher Thread");
	}
	

	public void run() {
		System.out.println("Running File Watch on: "+fileToWatch.getName());
		try {
			fileWatcher.listenToFile(fileToWatch);
		} catch (FileSystemException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void startWatching(){
		System.out.println("Starting File Watch");
		thread = new Thread(this);
		thread.start();
	}
	
	public void stopWatching(){
		System.out.println("Attempting to stop the file watch");
		if(thread != null){
			System.out.println("Interrupting Thread ");
			thread.interrupt();
			
		}
	}
	
}
